#include "Slimp.h"

/** @brief The default constructor
  *
  * userName will be the current users name.
  * IP defaults to the current IP address.
  * Port defaults to 9090.
  */
Slimp::Slimp()
{
    userName = Glib::get_user_name();
    gethostname(hostname, MAX_HOSTNAME_LENGTH);
    host = gethostbyname(hostname);
    if(!host) std::cerr << "gethostbyname() error\n";
    addr.sin_addr = *(struct in_addr*) host->h_addr_list[0];
    listenIP = inet_ntoa(addr.sin_addr);
    listenPort = "9090";

    MulticastReceiver mr(this, "0.0.0.0", MULTICAST_ADDRESS);

    PacketPtr a(new Packet(userName, MULTICAST_ADDRESS, MULTICAST_PORT));

    sendAnnounce(a);
}

/** @brief returns the user name
  *
  *
  */
std::string Slimp::getName() const
{
    return userName;
}

/** @brief returns the port
  *
  *
  */
std::string Slimp::getPort() const
{
    return listenPort;
}

/** @brief returns the IP address
  *
  *
  */
std::string Slimp::getIP() const
{
    return listenIP;
}

/** @brief returns the current version
  *
  *
  */
std::string Slimp::getVersion() const
{
    return AutoVersion::FULLVERSION_STRING;
}

/** @brief returns the hostname
  *
  *
  */
std::string Slimp::getHostname() const
{
    return host->h_name;
}

/** @brief send an announce to the network
  *
  *
  */
void Slimp::sendAnnounce(Packet::PacketPtr announce) const
{
    MulticastSender s(announce->getIP());
    s.sendMulticast(announce);
    std::cout << "Announce sent\n";
}

/** @brief called when receiving an announce
  *
  *
  */
void Slimp::receiveAnnounce(Packet::PacketPtr announce)
{
    std::cout << "Announce received\n";
}

/** @brief adds a tcp connection to an other slimp client
  *
  *
  */
void Slimp::addConnection(ConnectionPtr connection)
{
    connectionList.push_back(connection);
}

/** @brief adds a conversation
  *
  *
  */
void Slimp::addConversation(ConversationPtr conversation)
{
    conversationList.push_back(conversation);
}

/** @brief adds a new contact
  *
  *
  */
void Slimp::addContact(ContactPtr contact)
{
    contactList.push_back(contact);
}

/** @brief The default destructor
  *
  *
  */
Slimp::~Slimp()
{
    std::cout << "Sending disconnect\n";
    PacketPtr a(new Packet(userName + "disconnecct", MULTICAST_ADDRESS, MULTICAST_PORT));

    sendAnnounce(a);
}

/** @brief Parametized constructor
  *
  * \param ip sets the IP to listen on
  * \param port sets the port to listen on
  * \param name sets name of the user
  */
Slimp::Slimp(std::string ip, std::string port, std::string name)
{
    listenIP = ip;
    listenPort = port;
    userName = name;
}

